package com.telecom.sxint.app.api.controller.HistoryController;

import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telecom.sxint.app.api.controller.SystemController.App1SystemFileController.ExcelMerge;
import com.telecom.sxint.app.api.controller.SystemController.App1SystemFileController.ExcelMergeUtil;
import com.telecom.sxint.app.core.domain.entity.Historypojo.App1HistoryAssessment;
import com.telecom.sxint.app.core.domain.entity.Historypojo.App1QuarterHistoryPublicSheet;
import com.telecom.sxint.app.core.domain.entity.Historypojo.App1YunwangHistoryPublicSheet;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1YunwangWorkpojo.App1YunwangPublicSheet;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1countyIndicatorspojo.App1CountyIndicators;
import com.telecom.sxint.app.core.domain.entity.Systempojo.App1countyIndicatorspojo.App1QuarterPublicSheet;
import com.telecom.sxint.app.core.domain.entity.dto.EvaluationIndicatorsDTO;
import com.telecom.sxint.app.core.service.Historyservice.IApp1HistoryAssessmentService;
import com.telecom.sxint.app.core.service.Historyservice.IApp1QuarterHistoryPublicSheetService;
import com.telecom.sxint.app.core.service.Historyservice.IApp1YunwangHistoryPublicSheetService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Jxzoo
 * @version 2.0
 * @date 2024/10/15 14:23
 */
@RestController
@RequestMapping("/app1-systemhistory")
@Tag(name = "导出控制器", description = "信息导出管理")
@RequiredArgsConstructor
public class HistoryFileExportController {

    @Autowired
    private IApp1HistoryAssessmentService iApp1HistoryAssessmentService;
    @Autowired
    private IApp1QuarterHistoryPublicSheetService iApp1QuarterHistoryPublicSheetService;

    @Autowired
    private IApp1YunwangHistoryPublicSheetService iApp1YunwangHistoryPublicSheetService;
    /**
     * 生成excel文件下载，一个sheet
     * @param
     * @return
     */
    public static void downloadUnfilledToSheet(String excelName,String sheetName,List<List<String>>headers,List<Integer> mergeColumeIndex,int mergeRowIndex, HttpServletResponse response, Class cla, List list) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*="+fileName+ ".xlsx");
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteFont.setBold(true);
        headWriteCellStyle.setFillForegroundColor((short) 44);
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        // 从第二行后开始合并
        EasyExcel.write(response.getOutputStream(), cla)
                .head(headers)
                .registerWriteHandler(new ExcelMergeUtil(mergeRowIndex, mergeColumeIndex))
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                .autoCloseStream(Boolean.TRUE)
                .sheet(sheetName)
                .doWrite(list);
    }

    /**
     * 生成excel文件下载，多个sheet
     * @param
     * @return
     */
    public static void downloadUnfilledToSheets(String excelName, List<String> sheetNames, List<Integer> mergeColumeIndex, int mergeRowIndex, HttpServletResponse response, Class cla, List<List<App1HistoryAssessment>> lists) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode(excelName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*="+fileName+ ".xlsx");
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteFont.setBold(true);
        headWriteCellStyle.setFillForegroundColor((short) 44);
        //内容样式策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);

        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())
                .registerWriteHandler(new ExcelMergeUtil(mergeRowIndex,mergeColumeIndex))
                .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))
                .build();
        WriteSheet writeSheet =new WriteSheet();
        for(int i=0;i<lists.size();i++){
            lists.get(i).removeIf(app1Assessment -> StrUtil.isBlank(app1Assessment.getAssessmentItem())
                    &&StrUtil.isBlank(app1Assessment.getCategory())
                    &&StrUtil.isBlank(app1Assessment.getNotes())
                    &&StrUtil.isBlank(app1Assessment.getScore())
                    &&StrUtil.isBlank(app1Assessment.getWeight())
                    &&StrUtil.isBlank(app1Assessment.getCompletionValue())
                    &&StrUtil.isBlank(app1Assessment.getSelfScoringMethod())
                    &&StrUtil.isBlank(app1Assessment.getTargetValue())
                    &&StrUtil.isBlank(app1Assessment.getCompletionRateRank())
                    &&StrUtil.isBlank(app1Assessment.getTarget()));
            writeSheet = EasyExcel.writerSheet(i,sheetNames.get(i)).head(getAssHeader(sheetNames.get(i))).build();
            excelWriter.write(lists.get(i),writeSheet);
        }
        excelWriter.finish();
    }

    /**
     * 返回月度表头
     */
    private static List<List<String>> getAssHeader(String department){
        List<List<String>> line = new ArrayList<>();
        List<String> column = new ArrayList<>();
        column.add("被考核部门："+department);
        column.add("类别");
        line.add(column);
        column = new ArrayList<>();
        column.add("被考核部门："+department);
        column.add("考核项目");
        line.add(column);
        column = new ArrayList<>();
        column.add("被考核部门："+department);
        column.add("权重");
        line.add(column);
        column = new ArrayList<>();
        column.add("被考核部门："+department);
        column.add("目标");
        line.add(column);
        column = new ArrayList<>();
        column.add("被考核部门："+department);
        column.add("自评分计分方法");
        line.add(column);
        column = new ArrayList<>();
        column.add(" ");
        column.add("备注");
        line.add(column);
        column = new ArrayList<>();
        column.add(" ");
        column.add("目标值");
        line.add(column);
        column = new ArrayList<>();
        column.add(" ");
        column.add("完成值");
        line.add(column);
        column = new ArrayList<>();
        column.add(" ");
        column.add("完成率/排名|全省排名");
        line.add(column);
        column = new ArrayList<>();
        column.add(" ");
        column.add("得分");
        line.add(column);
        return line;
    }

    /**
     * 返回季度的表头
     *
     */
    private List<List<String>> getQuarterHeader(String sheetName){
        List<App1QuarterHistoryPublicSheet> quarterHeaders=iApp1QuarterHistoryPublicSheetService.selectFieldBySheetName(sheetName);
        int lens=quarterHeaders.size();
        List<List<String>> line = new ArrayList<>();
        List<String> column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldA());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldB());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldC());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldD());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldE());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldF());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldG());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldH());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldI());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldJ());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldK());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldL());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldM());
        }
        line.add(column);column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldN());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(quarterHeaders.get(i).getGeneralFieldO());
        }
        line.add(column);

        return line;
    }

    /**
     * 返回表头
     *
     */
    private List<List<String>> getYunwangHeader(String sheetName){
        List<App1YunwangHistoryPublicSheet> yunwangHeaders=iApp1YunwangHistoryPublicSheetService.selectFieldBySheetName(sheetName);
        int lens=yunwangHeaders.size();
        List<List<String>> line = new ArrayList<>();
        List<String> column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldA());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldB());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldC());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldD());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldE());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldF());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldG());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldH());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldI());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldJ());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldK());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldL());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldM());
        }
        line.add(column);column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldN());
        }
        line.add(column);
        column = new ArrayList<>();
        for(int i=0;i<lens;i++){
            column.add(yunwangHeaders.get(i).getGeneralFieldO());
        }
        line.add(column);

        return line;
    }

    /**
     * 云网历史记录excel文档导出
     * @param response
     * @return
     */
    @Operation(summary = "云网历史记录excel文档导出", description = "返回测试信息表分页")
    @GetMapping("exportYunwangHistory/{month}")
    public void exportAll(HttpServletResponse response,@PathVariable String month) throws IOException {
        List<Integer> mergeColumeIndex = new ArrayList<>();
        // 设置响应头
        mergeColumeIndex.add(0);
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = java.net.URLEncoder.encode(month+"云网工作", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
        ExcelWriter excelWriter = null;
        //一些样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteFont.setBold(true);
        headWriteCellStyle.setFillForegroundColor((short) 44);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        try {
            WriteSheet writeSheet=null;
            excelWriter = EasyExcel.write(response.getOutputStream()).build();
            List<String> sheetNames = iApp1YunwangHistoryPublicSheetService.selectAllSheetNames();
            List<List<App1YunwangHistoryPublicSheet>> yunwangSheets = new ArrayList<>();
            for(int i=0;i<sheetNames.size();i++){
                List<App1YunwangHistoryPublicSheet> list1 = iApp1YunwangHistoryPublicSheetService.selectDataBySheetName(sheetNames.get(i),month);
                yunwangSheets.add(list1);
            }

            for (int i = 0; i < yunwangSheets.size(); i++) {
                List<List<String>> lis = getYunwangHeader(sheetNames.get(i));
                int count=0;
                for(int j=lis.size();j>=0;j--){
                    if(areAllElementsEmpty(lis.get(j-1))) {
                        count++;
                    }else {
                        break;
                    }
                }
                writeSheet =EasyExcel.writerSheet(sheetNames.get(i))//sheet名称
                        .head(getYunwangHeader(sheetNames.get(i)))//表头
                        .registerWriteHandler(new ExcelMerge())//合并单元格
                        .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))//样式
                        .build();
                excelWriter.write(yunwangSheets.get(i), writeSheet);
            }

        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    /**
     * 月度历史记录excel文档导出,多个sheet
     * @param response
     * @return
     */
    @Operation(summary = "月度历史记录(某个月)excel文档导出", description = "返回测试信息表分页")
    @GetMapping("exportHistoryAssessment/{month}")
    public void exportAllAssessment(HttpServletResponse response,@PathVariable String month ) throws IOException {
        List<List<App1HistoryAssessment>> AssSheets = new ArrayList<>();
        List<String> departments = iApp1HistoryAssessmentService.selectAllDepartment();
        for (String department : departments) {
            List<App1HistoryAssessment> list1 = iApp1HistoryAssessmentService.selectWithDepartment(department,month);
            AssSheets.add(list1);
        }
        List<Integer> mergeColumeIndex = new ArrayList<>();
        //需要合并的列的编号
        mergeColumeIndex.add(0);
        mergeColumeIndex.add(1);
        mergeColumeIndex.add(3);
        mergeColumeIndex.add(4);
        downloadUnfilledToSheets(month+"月度考核",departments,mergeColumeIndex,2, response, App1HistoryAssessment.class, AssSheets);
    }

    /**
     * 季度历史记录excel文档导出
     * @param response
     * @return
     */
    @Operation(summary = "季度历史记录(某个月)excel文档导出", description = "返回测试信息表分页")
    @GetMapping("exportHistoryQuarterData/{month}")
    public void exportHistoryQuarterData(HttpServletResponse response,@PathVariable String month) throws IOException {
        List<Integer> mergeColumeIndex = new ArrayList<>();
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = java.net.URLEncoder.encode(month+"季度考核", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        ExcelWriter excelWriter = null;
        //一些样式
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setFillForegroundColor((short) 44);
        headWriteFont.setBold(true);
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
        //设置 自动换行
        contentWriteCellStyle.setWrapped(true);
        // 字体策略
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        try {
            WriteSheet writeSheet = null;
            excelWriter = EasyExcel.write(response.getOutputStream()).build();

            List<String> sheetNames = iApp1QuarterHistoryPublicSheetService.selectAllSheetNames();
            List<List<App1QuarterHistoryPublicSheet>> quarterSheets = new ArrayList<>();
            for(int i=0;i<sheetNames.size();i++){
                List<App1QuarterHistoryPublicSheet> list1 = iApp1QuarterHistoryPublicSheetService.selectDataBySheetName(sheetNames.get(i),month);
                quarterSheets.add(list1);
            }
            for (int i = 0; i < quarterSheets.size(); i++) {
                writeSheet = EasyExcel.writerSheet(sheetNames.get(i))//sheet名称
                        .head(getQuarterHeader(sheetNames.get(i)))//表头
                        .registerWriteHandler(new ExcelMerge())//合并单元格
                        .registerWriteHandler(new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle))//样式
                        .build();
                excelWriter.write(quarterSheets.get(i), writeSheet);
            }

        } finally {
            if (excelWriter != null) {
                excelWriter.finish();
            }
        }
    }

    public static boolean areAllElementsEmpty(List<?> list) {
        if (list == null) {
            throw new IllegalArgumentException("The list must not be null.");
        }

        for (Object element : list) {
            if (element == null) {
                continue; // null is considered empty
            }
            if (!(element instanceof String) || !((String) element).isEmpty()) {
                return false; // non-empty element found
            }
        }
        return true; // all elements are empty
    }


}
